#!/bin/bash
LIMIT=30  #自定义限制次数
LOGFILE="/var/log/black_ip.log" #日志路径
TIME=$(date '+%b %e %H')
BLACK_IP=$(grep "$TIME" /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '$1>$LIMIT{print $1":"$2}') #将一小时内>认证失败超过限定次数的ip抓出来
for i in $BLACK_IP
do
  IP=$(echo $i|awk -F: 'print $2')
  iptables-save | grep INPUT | grep DROP | grep $IP > /dev/null #判断该IP是否已经屏蔽
  if [ $? -gt 0 ];then
    iptables -A INPUT -s $IP -p tcp --dport 22 -j DROP #屏蔽ip
    NOW=$(date '+%Y-%m-%d %H:%M')
    echo -e "$NOW : $IP" >> ${LOGFILE}
  fi
done
